<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
  <title>公式插入</title>
  <!-- 引入 Vue 3 CDN -->
  <script src="./vue.global.js"></script>
  <!-- 引入 KaTeX CSS -->
  <link rel="stylesheet" href="./katex.min.css">
  <!-- 引入 KaTeX JS -->
  <script defer src="./katex.min.js"></script>
  <!-- 引入 axios -->
  <script src="./axios.min.js"></script>
  <style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }
    body {
      font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
      line-height: 1.5;
      color: #333;
      background-color: #f5f5f5;
    }
    .container {
      max-width: 640px;
      margin: 0 auto;
      padding: 15px;
      background-color: #fff;
      min-height: 100vh;
    }
    .btn {
      display: inline-block;
      padding: 8px 10px;
      background-color: #28b28b;
      color: white;
      border-radius: 4px;
      text-align: center;
      border: none;
      font-size: 16px;
      margin: 10px 0;
      width: 120px;
    }
    .btn:active {
      background-color: #1e8c7a;
    }

    .iframe {
      border: 1px solid #ddd;
      margin-bottom: 15px;
    }
    .option_value{
      color: #28b28b;
    }
    .textarea{
      border: 1px solid  #dcdfe6;
      width: 100%;
      padding: 10px;
      box-sizing: border-box;
      border-radius: 8px;
      color: #333333;
      font-size: 16px;
      font-family: "PingFang SC", "Hiragino Sans GB", "Helvetica Neue", Helvetica, Arial, sans-serif;
    }
    .textarea:focus{
      outline: none;
      border: 1px solid  #28b28b;
    }
    .flex_end{
      display: flex;
      justify-content: flex-end;
      align-items: center;
      gap: 0 20px;
    }
    .disabled{
      background-color: #ddd;
      color: #999;
    }
    .topic_text{
      color: #ffd766;
    }
    .topic_content{
      font-size: 16px;
      color: #333333;
      margin-bottom: 8px;
    }
  </style>
</head>
<body>
<div id="app" class="container">
  <div class="topic_content"><span class="topic_text">【{{topicText[topicInfo.topicType]}}】</span> <span v-html="renderedDescription(topicInfo.topicContent||topicInfo.content)"></span></div>
  <iframe ref="inputIFrameRef" :key="iframeKey" class="iframe" height="560px" width="100%" frameborder="0" src="./index.html"></iframe>
  <div class="flex_end">
    <button class="btn" @click="sureFormula">确认公式</button>
  </div>
  <div>
    当前题目 <span v-if="topicInfo.topicType==3">【第{{optionIndex+1}}空】</span> 公式部分预览：
  </div>
  <div class="option_value" v-html="renderedDescription(optionValue)"></div>
  <textarea v-if="topicType!=3" class="textarea" id="my_textarea" v-model="optionValue" cols="30" rows="10"></textarea>
  <div class="flex_end">
    <button class="btn" @click="saveAnswer">确定</button>
  </div>
</div>
<script>
  const { createApp, ref, onMounted } = Vue;

  createApp({
    setup() {
      // 获取路由query
      const query = new URLSearchParams(window.location.search);
      const optionValue = ref('');
      const optionIndex = query.get('optionIndex') - 0;
      const examPaperTopicId = query.get('examPaperTopicId');
      const topicType = query.get('topicType');
      const token = query.get('token');
      const topicUuid=query.get('uuid');
      const examType=query.get('examType');
      const multiAnswers = ref([]);
      const topicText = ref({
        0: "单选题 ",
        1: "多选题 ",
        2: "判断题",
        3: "填空题",
        4: "简答题",
        5: "操作题",
      })
      const iframeKey = ref(0);
      // 声明 ref
      const inputIFrameRef = ref(null);
      const topicInfo = ref({
        topicType:3,
        topicContent:'--'
      });

      // 确保 iframe 加载完成
      onMounted(() => {
        if (inputIFrameRef.value) {
          inputIFrameRef.value.onload = () => {
            console.log('iframe loaded');
          };
        }
      });

      const sureFormula = () => {
        if (!inputIFrameRef.value) {
          console.error('iframe 引用不存在');
          return;
        }

        try {
          const kfe = inputIFrameRef.value.contentWindow.kfe;
          if (!kfe) {
            console.error('kfe 对象不存在');
            return;
          }

          let latex = kfe.execCommand('get.source');
          latex = latex.replace(/\s/g, ''); // 去掉空格

          if (latex === '\\placeholder') {
            alert('请输入公式');
            return;
          }

          let str = `<p><span data-w-e-type="formula" data-w-e-is-void data-w-e-is-inline data-value="${latex}"></span></p>`;
          console.log('生成的公式:', str);
          optionValue.value= str;
          renderedDescription
          iframeKey.value++;
        } catch (error) {
          console.error('获取公式出错:', error);
        }
      };
      const renderedDescription = (description)=> {
        if (!description) {
          return description;
        }
        // 使用 DOMParser 解析 HTML 字符串
        const parser = new DOMParser();
        const doc = parser.parseFromString(description, 'text/html');

        // 查找所有的公式 span
        const formulaSpans = doc.querySelectorAll('span[data-w-e-type="formula"]');

        formulaSpans.forEach(span => {
          const latex = span.getAttribute('data-value');
          try {
            // 使用 KaTeX 渲染 LaTeX 公式
            const renderedFormula = katex.renderToString(latex, { throwOnError: false });
            // 创建一个新的 div 元素替换 spanvb
            const formulaCard = document.createElement('span');
            formulaCard.className = 'formula-card';
            formulaCard.innerHTML = renderedFormula;
            span.parentNode.replaceChild(formulaCard, span);
          } catch (error) {
            console.error('Error rendering LaTeX:', error);
          }
        });
        // 返回处理后的 HTML
        return doc.body.innerHTML;
      }
      const saveAnswer = () => {
        let params

          params = {
            topicUuid:topicUuid,
            topicId:examPaperTopicId,
            value:optionValue.value
          }


          axios.get(`https://cloud.metaxun.com/cloud/exam/stu/mistake/setTopicUuid`,
          { params:params,
            headers: {
              'Content-Type': 'application/json',
              'Authorization': 'Bearer ' + token
            }
          }
        ).then(res => {
          if(res.data.code == 200){
            alert('保存成功')
            console.log('保存成功');
          }
        }).catch(err => {
          console.log(err);
        });
      }
      let url= examType=='2'?`https://cloud.metaxun.com/cloud/exam/teacher/topic/info/`:`https://cloud.metaxun.com/cloud/exam/stu/getExamPaperTopicAnswer/`;
      const getPaperInfo = () => {
        axios.get(`${url}${examPaperTopicId}`,
          {
            headers: {
              'Content-Type': 'application/json',
              'Authorization': 'Bearer ' + token
            }
          }
        ).then(res => {
          const {code,data} = res.data
          if(code == 200){
            console.log(data)
            topicInfo.value = data
            multiAnswers.value = data.topicAnswer.answer.split('|')
            optionValue.value = multiAnswers.value[optionIndex]?multiAnswers.value[optionIndex]:''
          }
        }).catch(err => {
          console.log(err);
        });
      }
      getPaperInfo()
      return {
        sureFormula,
        getPaperInfo,
        topicInfo,
        multiAnswers,
        optionIndex,
        optionValue,
        topicText,
        renderedDescription,
        iframeKey,
        topicType,
        saveAnswer,
        inputIFrameRef
      };
    }
  }).mount('#app');
</script>
</body>
</html>
